package com.douma.lock;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

import java.util.concurrent.TimeUnit;

/**
 * 抖码课堂，专注中国程序员基础内功修炼
 * 官网：douma-tech.com
 * 公众号：抖码课堂
 *
 * @作者 : 老汤
 */
public class TestRedissonRedLock {
    public static void main(String[] args) {
        Config config1 = new Config();
        SingleServerConfig singleServerConfig1 = config1.useSingleServer();
        singleServerConfig1.setAddress("redis://192.168.126.131:6383");
        RedissonClient redissonClient1 = Redisson.create(config1);

        Config config2 = new Config();
        SingleServerConfig singleServerConfig2 = config2.useSingleServer();
        singleServerConfig2.setAddress("redis://192.168.126.131:6384");
        RedissonClient redissonClient2 = Redisson.create(config2);

        Config config3 = new Config();
        SingleServerConfig singleServerConfig3 = config3.useSingleServer();
        singleServerConfig3.setAddress("redis://192.168.126.131:6385");
        RedissonClient redissonClient3 = Redisson.create(config3);

        RLock lock1 = redissonClient1.getLock("mylock");
        RLock lock2 = redissonClient2.getLock("mylock");
        RLock lock3 = redissonClient3.getLock("mylock");

        // 创建红锁
        RLock redLock = redissonClient1.getRedLock(lock1, lock2, lock3);

        try {
            redLock.tryLock(10, 300, TimeUnit.SECONDS);

            System.out.println("do something ...");
            TimeUnit.SECONDS.sleep(100);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            redLock.unlock();
        }

        redissonClient1.shutdown();
        redissonClient2.shutdown();
        redissonClient3.shutdown();
    }
}
